//
//  KWTMGRNSettingSyncVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2024/7/29.
//

#import "KWTMGRNSettingSyncVC.h"
#import "KWTMGRNSettingSyncCell.h"
#import "RHSearchView.h"
#import "KWTMGRNSettingModel.h"
#import "RHEndPointModel.h"

@interface KWTMGRNSettingSyncVC ()<UITableViewDelegate,UITableViewDataSource,QMUITextFieldDelegate>
@property (nonatomic ,strong) UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *DeviceSelectArr;

@property(nonatomic,strong)NSMutableArray *searchArr;

@property(nonatomic,strong)QMUIButton *distributeBtn;


@property (nonatomic ,strong) RHSearchView *searchView;
@end

@implementation KWTMGRNSettingSyncVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"选择设备".rh_localized;
    [self setupUI];
    [self.distributeBtn setTitle:[NSString stringWithFormat:@"%@(%zd/%zd)",@"同步".rh_localized,self.DeviceSelectArr.count,self.totalDevArr.count] forState:UIControlStateNormal];
}


- (void)setupUI{
    
    _searchView = [[RHSearchView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 55)];
    [self.view addSubview:_searchView];
    _searchView.delegate = self;
    _searchView.searchTextField.placeholder = @"请输入".rh_localized;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setSeparatorColor:UIColor.clearColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[KWTMGRNSettingSyncCell class] forCellReuseIdentifier:@"KWTMGRNSettingSyncCell"];
    [self.view addSubview:_tableView];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        //_resultTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
        //_resultTableView.sectionHeaderTopPadding = 0;
    }
    
    _distributeBtn = [[QMUIButton alloc]init];
    [_distributeBtn setTitle:@"同步".rh_localized forState:UIControlStateNormal];
    [_distributeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_distributeBtn setBackgroundColor:CMainColorGreen];
    _distributeBtn.titleLabel.font = [UIFont boldSystemFontOfSize:19];
    _distributeBtn.layer.cornerRadius = 8;
    _distributeBtn.layer.masksToBounds = YES;
    [self.view addSubview:_distributeBtn];
    [_distributeBtn addTarget:self action:@selector(syncOtherDevice) forControlEvents:UIControlEventTouchUpInside];
    [_distributeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(20);
        make.right.mas_offset(-20);
        make.bottom.mas_offset(-kSafe_bottom-20);
        make.height.offset(kScaleW(45));
    }];
    
    kWeakSelf;
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(weakSelf.searchView.mas_bottom);
        make.bottom.equalTo(weakSelf.distributeBtn.mas_top).offset(-20);
    }];
    
    _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
}


#pragma mark ----- 获取同一电站下的同一类型的设备 ------
//-(void)getDeviceListOfPlant
//{
//    [self.DeviceSelectArr removeAllObjects];
//    
//    [QMUITips showLoadingInView:self.view];
//    NSDictionary *para = @{
//                           @"pageNum":@(self.currentPage),
//                           @"pageSize":@(self.numOfPage),
//                           @"deviceId":ValidNullData(self.deviceModel.deviceId),
//                           @"deviceName":ValidNullData(self.searchView.searchTextField.text)
//    };
//    [RHDeviceModel startGetWithCompletionAPIKey:H_deviceListOfPlant argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
//        if(resultModel.code == 200){
//            NSInteger total = [request.responseObject[@"total"] integerValue];
//            self.totalPage = total%self.numOfPage? total/self.numOfPage+1 : total/self.numOfPage;
//            NSMutableArray *arr = [NSMutableArray arrayWithArray:resultModel.data];
//            //下拉刷新
//            if(self.requestType == RequestTypeRefresh){
//                [self.tableView endHeaderRefresh];
//                self.totalDevArr = arr;
//            }else{//上拉加载
//                [self.tableView endFooterRefresh];
//                [self.totalDevArr addObjectsFromArray:arr];
//            }
//            if(self.currentPage >= self.totalPage){
//                [self.tableView endFooterRefreshCustomWithNoMoreData];
//            }
//            [self.tableView reloadData];
//           
//            if(self.totalDevArr.count == 0){
//                [self.tableView endFooterRefreshWithNoMoreData];
//            }
//            
//            [self.distributeBtn setTitle:[NSString stringWithFormat:@"%@(%zd/%zd)",@"同步".rh_localized,self.DeviceSelectArr.count,self.totalDevArr.count] forState:UIControlStateNormal];
//        }
//        
//    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
//           [self.tableView endHeaderRefresh];
//           [self.tableView endFooterRefresh];
//    }];
//}

#pragma mark ------ 同步设置
-(void)syncOtherDevice
{
    
    
    if (self.DeviceSelectArr.count == 0) {
        return;
    }
    
    NSMutableDictionary *requestPara = [NSMutableDictionary dictionary];
    //要同步的设备
    NSMutableArray *deviceArr = [NSMutableArray array];
    [self.DeviceSelectArr enumerateObjectsUsingBlock:^(RHDeviceModel*  _Nonnull devModel, NSUInteger idx, BOOL * _Nonnull stop) {
        [deviceArr addObject:devModel.deviceId];
    }];
    
    if (self.selectBlock) {
        self.selectBlock(deviceArr.copy);
    }
    [self.navigationController popViewControllerAnimated:YES];
    return;//只选择设备,不调接口,统一在外面调
    
    //----------------------------------------------------
    
    [requestPara setObject:deviceArr forKey:@"deviceIds"];
    
    //参数的body
    NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
    NSMutableArray *paraListArr = [NSMutableArray array];
    RHEndPointModel *endpointModel = [self.endPointTypeModel.nodes firstObject];
    NSDictionary *endPointDic = @{@"dataType":@"string",
                                  @"paramName":@"sn",
                                  @"value":ValidNullData(endpointModel.sn)};
    [paraListArr addObject:endPointDic];
  
    
    [self.dataArr enumerateObjectsUsingBlock:^(KWTMGRNSettingModel * _Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
        [sectionModel.rows enumerateObjectsUsingBlock:^(KWTMGRNSettingModel * _Nonnull rowModel, NSUInteger idx, BOOL * _Nonnull stop) {
            //时间校准 (单独设置,这里过滤掉)
            if([rowModel.type isEqualToString:@"date"]){
                NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                formatter.dateFormat = @"yyyy/MM/dd HH:mm:ss";
                NSDate *date = [formatter dateFromString:rowModel.content];
                [self processTimeParams:paraListArr date:date];
                return;
            }
            
            //充放电时间配置
            if ([rowModel.type isEqualToString:@"time"]) {
                [rowModel.items enumerateObjectsUsingBlock:^(KWTMGRNSettingModel * _Nonnull itemModel, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (itemModel.content.length == 0) {
                        return;
                    }
                    NSMutableDictionary *itemDic = [NSMutableDictionary dictionary];
                    [itemDic setObject:itemModel.format forKey:@"dataType"];
                    [itemDic setObject:itemModel.key forKey:@"paramName"];
                    [itemDic setObject:itemModel.content forKey:@"value"];
                    [itemDic setObject:@(itemModel.regAddr) forKey:@"regAddr"];
                    [itemDic setObject:@(itemModel.num) forKey:@"num"];
                    [itemDic setObject:@(itemModel.offset) forKey:@"offset"];
                    [paraListArr addObject:itemDic];
                    
                    //时间
                    if ([itemModel.type isEqualToString:@"date"]) {
                        NSString *content = [itemModel.content stringByReplacingOccurrencesOfString:@":" withString:@""];
                        [itemDic setObject:ValidNullData(content) forKey:@"value"];
                    }
                }];
            }
            //工作模式 充电使能
            if ([rowModel.type isEqualToString:@"switch"]||[rowModel.type isEqualToString:@"select"]) {
                if (rowModel.content.length == 0) {
                    return;
                }
                NSMutableDictionary *textDic = [NSMutableDictionary dictionary];
                [textDic setObject:rowModel.format forKey:@"dataType"];
                [textDic setObject:rowModel.key forKey:@"paramName"];
                [textDic setObject:rowModel.content forKey:@"value"];
                [textDic setObject:@(rowModel.regAddr) forKey:@"regAddr"];
                [textDic setObject:@(rowModel.num) forKey:@"num"];
                [textDic setObject:@(rowModel.offset) forKey:@"offset"];
                [paraListArr addObject:textDic];
            }
            
        }];
     
        //移除 json文件里两个无关的自定义参数参数
        NSMutableArray *removeArr = [NSMutableArray array];
       
        [paraListArr enumerateObjectsUsingBlock:^(NSMutableDictionary*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj[@"paramName"] isEqualToString:@"SystemTimeAligned"]||[obj[@"paramName"] isEqualToString:@"Inv1_chgPri"]) {
                [removeArr addObject:obj];
            }
        }];
       
        if (removeArr.count>0) {
            [paraListArr removeObjectsInArray:removeArr];
        }
        
        
    }];
    

    if (paraListArr.count == 0) {
        return;
    }
    [bodyDic setObject:paraListArr forKey:@"commandParamList"];
    [requestPara setValue:bodyDic forKey:@"protocolBody"];
    
    //参数的头部
    NSString *randomStr = [NSString generateRandomLetter:15];
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
    NSDictionary *headContent = @{
        @"cmdId": randomStr,
        @"deviceId": self.deviceModel.deviceId,
        @"deviceType": self.deviceModel.productTypeCode,
        @"endpointCode":endpointModel.endpointCode,
        @"paramCount":@(paraListArr.count-1),
        @"sn":endpointModel.sn,
        @"messageType": @(1),//下行
        @"namespace": @"ParamSetSingle",
        @"payloadVersion": @(1),
        @"timestamp": @((NSInteger)interval)
      };
    [requestPara setValue:headContent forKey:@"protocolHead"];
    
    [QMUITips showLoading:@"设置中...".rh_localized inView:self.view];
    [BaseModel startWithCompletionAPIKey:H_deviceConfigSync argument:requestPara requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"设置成功".rh_localized];
            
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
}

//处理麦格瑞能时间校准格式
-(void)processTimeParams:(NSMutableArray*)paramList date:(NSDate*)date
{
    NSArray *keys = @[@"Inv3_RTCYear",@"Inv3_RTCMonth",@"Inv3_RTCDay",@"Inv3_RTCHour",@"Inv3_RTCMinute",@"Inv3_RTCSecond"];
    NSArray *value = @[@(date.year%100),@(date.month),@(date.day),@(date.hour),@(date.minute),@(date.second)];
    [keys enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary *timeDic = [NSMutableDictionary dictionary];
        NSString *valueStr = [NSString stringWithFormat:@"%02ld",[value[idx] integerValue]];
        [timeDic setObject:@"int" forKey:@"dataType"];
        [timeDic setObject:keys[idx] forKey:@"paramName"];
        [timeDic setObject:valueStr forKey:@"value"];
        [timeDic setObject:@(1150+idx) forKey:@"regAddr"];//1150-1155
        [timeDic setObject:@(16) forKey:@"num"];
        [timeDic setObject:@(0) forKey:@"offset"];
        [paramList addObject:timeDic];
    }];
   
}


#pragma mark ------ tableView delegate --------

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.searchArr.count>0) {
        return self.searchArr.count;
    }
    return self.totalDevArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KWTMGRNSettingSyncCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KWTMGRNSettingSyncCell"];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    RHDeviceModel *deviceModel;
    if (self.searchArr.count>0) {
        deviceModel = self.searchArr[indexPath.row];
    }else{
        deviceModel = self.totalDevArr[indexPath.row];
    }
    cell.deviceModel = deviceModel;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    RHDeviceModel *deviceModel  = self.totalDevArr[indexPath.row];
    
    kWeakSelf;
    //如果设备是离线状态
    if([deviceModel.status isEqualToString:@"1"]){
        return;
    }
        
    deviceModel.isSelected = !deviceModel.isSelected;
    if(deviceModel.isSelected){
        [self.DeviceSelectArr addObject:deviceModel];
    }else{
        [self.DeviceSelectArr removeObject:deviceModel];
    }
    [self.tableView reloadData];
        
    
    
    
  
    [self.distributeBtn setTitle:[NSString stringWithFormat:@"%@(%zd/%zd)",@"同步".rh_localized,self.DeviceSelectArr.count,self.totalDevArr.count] forState:UIControlStateNormal];
    
}

#pragma mark ------- textField delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{

    for (RHDeviceModel* model in self.totalDevArr) {
        if ([model.deviceId.uppercaseString containsString:textField.text.uppercaseString]) {
            if (![self.searchArr containsObject:model]) {
                [self.searchArr addObject:model];
            }
        }
    }
    
    [self.searchView resignFirstResponder];
    [self.tableView reloadData];
    
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.searchArr removeAllObjects];
        [self.tableView reloadData];
        [self.searchView resignFirstResponder];
    });
    return YES;
}


-(NSMutableArray *)DeviceSelectArr
{
    if(!_DeviceSelectArr){
        _DeviceSelectArr = [NSMutableArray array];
    }
    return _DeviceSelectArr;
}


-(NSMutableArray *)totalDevArr
{
    if(!_totalDevArr){
        _totalDevArr = [NSMutableArray array];
    }
    return _totalDevArr;
}

-(NSMutableArray *)searchArr
{
    if(!_searchArr){
        _searchArr = [NSMutableArray array];
    }
    return _searchArr;
}
@end
